import ActionSheet from '@/pages/common/ActionSheet';
import { BottomSheetModal } from '@gorhom/bottom-sheet';
import React, { ReactNode, useCallback, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { TouchableOpacity, Alert, Text, Platform, Linking } from 'react-native';
import FastImage, { Source } from 'react-native-fast-image';
import {
  Asset,
  launchCamera,
  launchImageLibrary,
} from 'react-native-image-picker';
import {
  PERMISSIONS,
  requestMultiple,
  RESULTS,
} from 'react-native-permissions';
import { Icon } from 'tsun-smart-ui';
import AlertDialog from './AlertDialog';
import PermissionNotGrantedDialog from './PermissionNotGrantedDialog';
import StringUtils from '@/utils/StringUtils';
import PermissionUtils from '@/utils/PermissionUtils';

type AvatarImagePickerProps = {
  image: Asset | string | undefined;
  title?: string;
  resubmitTitle?: string;
  onPickNewImage: (image: Asset) => void;
  preview?: boolean;
};

const AvatarImagePicker: React.FC<AvatarImagePickerProps> = (props) => {
  const { t } = useTranslation();
  const bottomSheetRef = useRef<BottomSheetModal>(null);

  const actions = [
    {
      title: t('sys.app.camera'),
      onPress: async () => {
        const result = await PermissionUtils.checkPermission(PERMISSIONS.IOS.CAMERA)
        if (result.status === RESULTS.DENIED) {
          PermissionUtils.showPermissionNotGrantedAlert()
          return
        }
        const asset = await launchCamera({
          mediaType: 'photo',
        });
        if (asset.assets && asset.assets.length > 0) {
          props.onPickNewImage(asset.assets[0]);
        }
      },
    },
    {
      title: t('sys.app.album'),
      onPress: async () => {
        const asset = await launchImageLibrary({
          mediaType: 'photo',
          selectionLimit: 1,
        });
        if (asset.assets && asset.assets.length > 0) {
          props.onPickNewImage(asset.assets[0]);
        }
      },
    },
  ];

  const onPickNewImage = useCallback(async () => {
    bottomSheetRef.current?.present();
  }, []);

  const haveImage = Boolean(props.image);
  // const borderStyle = haveImage
  //   ? ''
  //   : 'border-dashed border-[1px] border-line2 border-1 border-gray-300';
  const title =
    props.title ?? t('sys.app.upload.avatar', { defaultValue: '上传封面' });
  let image: number | Source;
  if (haveImage) {
    const imageUri =
      typeof props.image === 'string' ? props.image : props.image!.uri;
    image = { uri: StringUtils.toImageUri(imageUri) };
  } else {
    image = require('@/assets/imgs/station-placeholder.png');
  }
  const preview = props.preview ?? false;
  return (
    <>
      <TouchableOpacity
        className={`self-stretch justify-center items-center gap-3 rounded-xl aspect-video bg-text6`}
        onPress={onPickNewImage}
        disabled={preview}
      >
        <FastImage
          className="absolute top-0 right-0 bottom-0 left-0 rounded-xl"
          source={image}
          resizeMode="cover"
        />
        {!preview && (
          <Text className="absolute bottom-0 left-0 right-0 py-2 bg-black/50 text-center text-white/80 rounded-bl-xl rounded-br-xl text-[12px]">
            {props.resubmitTitle ??
              t('sys.app.upload.avatar', { defaultValue: '上传封面' })}
          </Text>
        )}
      </TouchableOpacity>
      <ActionSheet
        ref={bottomSheetRef}
        actions={actions}
        title={t('sys.app.pls.select.station.avatar')}
      />
    </>
  );
};

export default React.memo(AvatarImagePicker);
